/**
 * Created by lmn98 on 2017/5/19.
 */
var express = require('express');
var router = express.Router();
var err = require('../my_modules/error');
var parseTorrent = require('parse-torrent');
var path = require('path');
var fs = require('fs');
var db = require('../my_modules/my_sequlize');
var tc = require('../my_modules/torrent_client');
var config = require('../config');

router.get('/detail', function (req, res) {
    var torrent;
    var parsed;
    try {
        if(req.query.dir){
            torrent = fs.readFileSync(path.join(config.file.temp, req.query.dir+'.torrent'));
        }else if(req.session.magnet){
            torrent = req.session.magnet;
        }else {
            res.json(err.fileNotExist);
            return;
        }
        parsed = parseTorrent(torrent);
        res.json({
            name: parsed.name,
            length: parsed.length,
            files: parsed.files,
            infoHash: parsed.infoHash
        })
    } catch (e) {
        // the torrent file was corrupt
        res.session.magnet=null;
        res.json(err.fileErr)
    }
});

router.put('/detail', function (req, res) {
    var dir = req.body.dir;
    var magnet = req.body.magnet;
    var torrent;
    if(dir){
        torrent = fs.readFileSync(path.join(req.session.root,dir+'.torrent'));
    }else if(magnet){
        req.session.magnet = magnet;
        torrent = magnet;
    }else {
        res.json(err.paraErr);
        return;
    }
    var parsed;
    try {
        parsed = parseTorrent(torrent);
        res.json({
            name: parsed.name,
            length: parsed.length,
            files: parsed.files,
            infoHash: parsed.infoHash
        })
    } catch (e) {
        // the torrent file was corrupt
        res.json(err.fileErr)
    }
});

router.post('/BT', function (req, res) {
    var dir = req.body.dir;
    var temp = req.body.temp;
    var saveDir = req.body.saveDir;
    var files = req.body.files;
    var name = req.body.name;
    if((!dir && !temp) || !files || !name || !saveDir) {
        res.json(err.paraErr);
        return;
    }
    var parsed;
    try {
        var torrent;
        if(dir){
            torrent = fs.readFileSync(path.join(req.session.root,dir));
        }else if(temp){
            torrent = fs.readFileSync(path.resolve(temp));
        }
        parsed = parseTorrent(torrent);
        parsed.name = name;
        parsed.files = files;
        parsed.length = 0;
        files.forEach(function (e) {
            parsed.length += e.length;
        });
        db.torrent.find({
            where: {infoHash: parsed.infoHash}
        }).then(function(tor){
            if(tor){
                res.json(err.fileHasExist);
                return;
            }
            tc.add(req.session.username, parsed, req.session.root+saveDir, function (msg) {
                if(!msg.error){
                    db.torrent.create({
                        infoHash: parsed.infoHash,
                        userId: req.session.userId,
                        name: parsed.name,
                        dir: dir,
                        path: saveDir,
                        size: parsed.length,
                        state: msg.state  //0 ing, 1 pause, 2 finish, 3 deleted
                    }).then(function (t) {
                        if(!t) return;
                        files.forEach(function (e) {
                            e.torrentInfoHash = t.infoHash;
                            db.torrent_file.create(e)
                        });
                        if(temp){
                            fs.rmdirSync(path.resolve(temp))
                        }
                        res.json(msg)
                    })
                }else
                    res.json(msg)
            })
        });
    } catch (e) {
        // the torrent file was corrupt
        console.log(e);
        res.json(err.fileErr)
    }
});
//magnet:?xt=urn:btih:e7b56383ac606860577f79b89f58895b0baffb89
router.post('/magnet', function (req, res) {
    var magnet = req.session.magnet;
    var name = req.body.name;
    var files = req.body.files;
    var saveDir = req.body.saveDir;
/*    if(!magnet || !files || !saveDir || !name) {
        res.json(err.paraErr);
        return;
    }*/
    var parsed;
    try {
        parsed = parseTorrent(magnet);
        parsed.name = name;
        parsed.files = files;
        parsed.length = 0;
        files.forEach(function (e) {
            parsed.length += e.length;
        });
        db.torrent.find({
            where: {infoHash: parsed.infoHash}
        }).then(function(tor){
            if(tor){
                res.json(err.fileHasExist);
                return;
            }
            tc.add(req.session.username, magnet, req.session.root+saveDir, function (msg) {
                if(!msg.error){
                    db.torrent.create({
                        infoHash: parsed.infoHash,
                        userId: req.session.userId,
                        name: parsed.name,
                        dir: magnet,
                        path: saveDir,
                        size: parsed.length,
                        state: msg.state  //0 ing, 1 pause, 2 finish, 3 deleted
                    }).then(function (t) {
                        if(!t) return;
                        files.forEach(function (e) {
                            e.torrentInfoHash = t.infoHash;
                            db.torrent_file.create(e)
                        });
                        res.json(msg)
                    })
                }else
                    res.json(msg)
            })
        });
    } catch (e) {
        // the torrent file was corrupt
        console.log(e);
        res.json(err.fileErr)
    }
});

router.get('/status', function (req, res) {
    tc.status(req.session.username, function (msg) {
        if(msg.error){
            res.json(msg);
            return;
        }
        db.torrent.findAll({
            include: [{
                model: db.user,
                where: {
                    id: req.session.userId
                },
                attributes: ['id']
            }]
        }).then(function (torrents) {
            torrents.forEach(function (t) {
                if(msg.torrents.hasOwnProperty(t.infoHash)){
                    t.dataValues.downloaded = msg.torrents[t.infoHash].downloaded;
                    t.dataValues.downloadSpeed = msg.torrents[t.infoHash].downloadSpeed;
                    t.dataValues.progress = msg.torrents[t.infoHash].progress;
                }
            });
            msg.torrents = torrents;
            res.json(msg)
        })
    })
});

router.put('/pause', function (req, res) {
    var infoHash = req.body.infoHash;
    if(!infoHash){
        res.json(err.paraErr);
        return;
    }
    tc.pause(req.session.username, infoHash, function (msg) {
        res.json(msg)
    })
});

router.put('/resume', function (req, res) {
    var infoHash = req.body.infoHash;
    if(!infoHash){
        res.json(err.paraErr);
        return;
    }
    tc.resume(req.session.username, infoHash, function (msg) {
        res.json(msg)
    })
});

router.put('/destroy', function (req, res) {
    var infoHash = req.body.infoHash;
    if(!infoHash){
        res.json(err.paraErr);
        return;
    }
    tc.destroy(req.session.username, infoHash, function (msg) {
        res.json(msg)
    })
});

router.delete('/:infoHash', function (req, res) {
    var infoHash = req.params.infoHash;
    if(!infoHash){
        res.json(err.paraErr);
        return;
    }
    tc.destroy(req.session.username, infoHash, function (msg) {
        db.torrent_file.destroy({
            where: {
                torrentInfoHash: infoHash
            }
        }).then(function () {
            db.torrent.destroy({
                where: {
                    infoHash: infoHash
                }
            }).then(function () {
                res.json(err.success);
            })
        });
    })
});

router.get('/files', function (req, res) {
    var infoHash = req.query.infoHash;
    if(!infoHash){
        res.json(err.paraErr);
        return;
    }
    tc.torrentStatus(req.session.username, infoHash, function (msg) {
        res.json(msg)
    })
});

module.exports = router;
